from typing import Any, List, Optional

from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.ext.asyncio import AsyncSession

from app.api import deps
from app.crud import message as crud_message
from app.db.session import get_db
from app.schemas.analysis import (ChatAnalysis, OptimizationRequest,
                                 OptimizationResponse, PUADetectionResult)
from app.schemas.messages import Message, MessageQuery
from app.services.analysis.chat_analyzer import chat_analyzer
from app.services.analysis.pua_detector import pua_detector

router = APIRouter()


@router.post("/chat", response_model=ChatAnalysis)
async def analyze_chat(
    session_id: Optional[int] = None,
    contact_id: Optional[int] = None,
    relationship_type: Optional[str] = None,
    start_msg_id: Optional[int] = None,
    end_msg_id: Optional[int] = None,
    limit: int = 100,
    db: AsyncSession = Depends(get_db),
) -> Any:
    """
    分析聊天记录
    
    - **session_id**: 会话ID
    - **contact_id**: 联系人ID
    - **relationship_type**: 关系类型
    - **start_msg_id**: 起始消息ID
    - **end_msg_id**: 结束消息ID
    - **limit**: 最大消息数量
    """
    # 构建查询条件
    query = MessageQuery(
        session_id=session_id,
        contact_id=contact_id,
        limit=limit
    )
    
    # 获取消息记录
    messages = await crud_message.get_messages_by_query(db, query=query)
    
    if not messages:
        raise HTTPException(
            status_code=404,
            detail="No messages found with the given criteria"
        )
    
    # 将ORM对象转换为字典
    messages_dict = [
        {
            "id": msg.id,
            "contact_id": msg.contact_id,
            "session_id": msg.session_id,
            "direction": msg.direction,
            "msg_type": msg.msg_type,
            "content": msg.content,
            "sent_at": msg.sent_at,
            "status": msg.status
        }
        for msg in messages
    ]
    
    # 分析聊天内容
    analysis = await chat_analyzer.analyze_chat(
        messages=messages_dict,
        relationship_type=relationship_type
    )
    
    return analysis


@router.post("/optimize", response_model=OptimizationResponse)
async def optimize_message(
    optimization_request: OptimizationRequest,
    db: AsyncSession = Depends(get_db),
) -> Any:
    """
    优化消息文本
    
    根据关系类型和聊天目标，生成优化建议
    """
    # 获取上下文消息
    context_messages = []
    if optimization_request.context_messages:
        context_msg_ids = optimization_request.context_messages
        for msg_id in context_msg_ids:
            msg = await crud_message.get(db, id=msg_id)
            if msg:
                context_messages.append({
                    "id": msg.id,
                    "direction": msg.direction,
                    "content": msg.content,
                    "sent_at": msg.sent_at
                })
    
    # 生成优化建议
    suggestions = await chat_analyzer.generate_suggestions(
        text=optimization_request.text,
        relationship_type=optimization_request.relationship_type,
        chat_goal=optimization_request.chat_goal,
        context_messages=context_messages
    )
    
    # 分析原文
    text_analysis = await chat_analyzer.analyze_chat(
        messages=[{"content": optimization_request.text}],
        relationship_type=optimization_request.relationship_type
    )
    
    # 构建响应
    response = OptimizationResponse(
        original_text=optimization_request.text,
        suggestions=suggestions,
        analysis=text_analysis
    )
    
    return response


@router.post("/detect-pua", response_model=PUADetectionResult)
async def detect_pua(
    text: str,
) -> Any:
    """
    检测PUA话术
    
    分析文本中可能存在的PUA话术和操控模式
    """
    result = await pua_detector.detect_pua(text)
    return result


@router.post("/analyze-pua-history")
async def analyze_pua_history(
    contact_id: Optional[int] = None,
    session_id: Optional[int] = None,
    limit: int = 200,
    db: AsyncSession = Depends(get_db),
) -> Any:
    """
    分析PUA历史趋势
    
    分析特定联系人或会话的PUA模式和趋势
    """
    # 获取消息记录
    query = MessageQuery(
        contact_id=contact_id,
        session_id=session_id,
        limit=limit
    )
    
    messages = await crud_message.get_messages_by_query(db, query=query)
    
    if not messages:
        raise HTTPException(
            status_code=404,
            detail="No messages found with the given criteria"
        )
    
    # 将ORM对象转换为字典
    messages_dict = [
        {
            "id": msg.id,
            "contact_id": msg.contact_id,
            "session_id": msg.session_id,
            "direction": msg.direction,
            "msg_type": msg.msg_type,
            "content": msg.content,
            "sent_at": msg.sent_at,
            "status": msg.status
        }
        for msg in messages
    ]
    
    # 分析PUA历史
    history_analysis = await pua_detector.analyze_pua_history(messages_dict)
    
    return history_analysis